package com.scu.dao;

import com.scu.entity.Admin;
import com.scu.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class AdminDao {
    //添加一个管理员
    public int insert(Admin admin) throws SQLException {
        //1. 连接
        Connection conn = JDBCUtil.getConnection();

        //2. sql
        String sql = "INSERT INTO ADMIN (admin_id,password,name,phone,email) VALUES(?,?,?,?,?)";
        PreparedStatement prep = conn.prepareStatement(sql);
        prep.setInt(1,admin.getAdmin_id());
        prep.setString(2,admin.getPassword());
        prep.setString(3,admin.getName());
        prep.setString(4,admin.getPhone());
        prep.setString(5,admin.getEmail());

        //3. 结果
        int row = prep.executeUpdate();

        //4. 关闭连接
        conn.close();

        return row;
    }

    //删除
    public int delete(int admin_id) throws SQLException {
        //1. 连接
        Connection conn = JDBCUtil.getConnection();

        //2. sql
        String sql = "delete from admin where admin_id=?";
        PreparedStatement prep = conn.prepareStatement(sql);
        prep.setInt(1,admin_id);

        //3. 结果
        int row = prep.executeUpdate();

        //4. 关闭连接
        conn.close();

        return row;
    }

    public List<Admin> findAllAdmin() throws SQLException {
        //1. 连接
        Connection conn = JDBCUtil.getConnection();

        //2. sql
        String sql = "select * from admin";
        PreparedStatement prep = conn.prepareStatement(sql);

        //3. 结果
        ResultSet rs = prep.executeQuery();
        //处理结果
        List<Admin> list = new ArrayList<Admin>();
        while(rs.next()){
            //rs代表的就是每一行
            Admin admin = new Admin();

            int admin_id = rs.getInt("admin_id");
            String password = rs.getString("password");
            String name = rs.getString("name");
            String phone = rs.getString("phone");
            String email = rs.getString("email");


            admin.setAdmin_id(admin_id);
            admin.setPassword(password);
            admin.setName(name);
            admin.setPhone(phone);
            admin.setEmail(email);

            list.add(admin);
        }

        //4. 关闭连接
        conn.close();

        return list;
    }

    public static void main(String[] args) throws SQLException {
        List<Admin> list = new AdminDao().findAllAdmin();
        System.out.println(list);
    }
}
